<template>
    <view class="chat-page">
        <scroll-view class="chat-container" :scroll-y="true" :scroll-into-view="scrollIntoView" scroll-with-animation>
            <view v-for="(msg, index) in messages" :key="index" class="chat-bubble" :class="msg.role">
                <text>{{ msg.content }}</text>
            </view>
            <view :id="bottomAnchor" />
        </scroll-view>

        <view class="chat-input-bar">
            <textarea v-model="inputText" placeholder="请输入..." class="input-box" />
            <view class="buttons">
                <button class="send-btn" @click="sendMessage" :disabled="loading">
                    {{ loading ? "发送中..." : "发送" }}
                </button>
                <button @click="clearMessages" class="clear-btn">清空</button>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">

// const md = new MarkdownIt()
// console.log(md.render('# 标题'))  // 应该输出 <h1>标题</h1>
import { ref, onMounted, nextTick } from "vue";
import { apiDeepSeekChat } from "../../apis/deepseek";
const inputText = ref('');
const messages = ref<{ role: 'user' | 'assistant'; content: string }[]>([]);
const scrollIntoView = ref('');
const bottomAnchor = 'bottom-anchor';
const loading = ref(false);

const scrollBottom = () => {
    nextTick(() => {
        scrollIntoView.value = bottomAnchor;
    });
};

onMounted(() => {
    const local = uni.getStorageSync('deepseek_history');
    if (Array.isArray(local)) {
        messages.value = local;
        scrollBottom();
    }
});

const sendMessage = async () => {
    if (!inputText.value.trim() || loading.value) return;

    const userMsg = { role: 'user', content: inputText.value.trim() };
    messages.value.push(userMsg);

    const assistantMsg = { role: 'assistant', content: '' };
    messages.value.push(assistantMsg);

    inputText.value = '';
    loading.value = true;
    scrollBottom();

    try {
        const reply = await apiDeepSeekChat(messages.value);

        // 打字机流式显示效果
        let i = 0;
        const timer = setInterval(() => {
            if (i < reply.length) {
                assistantMsg.content += reply[i];
                i++;
                scrollBottom();
            } else {
                clearInterval(timer);
                loading.value = false;
                saveHistory();
            }
        }, 40); // 每40ms打一个字
    } catch (error) {
        loading.value = false;
        console.error(error);
        uni.showToast({ title: "请求失败", icon: "none" });
    }
};

const saveHistory = () => {
    uni.setStorageSync('deepseek_history', messages.value);
};

const clearMessages = () => {
    uni.showModal({
        title: "确认清空？",
        success: (res) => {
            if (res.confirm) {
                messages.value = [];
                uni.removeStorageSync('deepseek_history');
            }
        }
    });
};
</script>

<style scoped lang="scss">
.chat-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: #f6f8fa;
}

.chat-container {
    flex: 1;
    padding: 20rpx;
}

.chat-bubble {
    padding: 16rpx;
    margin: 10rpx 0;
    border-radius: 12rpx;
    max-width: 70%;
    word-break: break-word;
}

.chat-bubble.user {
    align-self: flex-end;
    background-color: #d4f5ff;
}

.chat-bubble.assistant {
    align-self: flex-start;
    background-color: #f5f5f5;
}

.chat-input-bar {
    padding: 20rpx;
    background: #fff;
    display: flex;
    flex-direction: column;
}

.input-box {
    background: #f6f6f6;
    border-radius: 8rpx;
    padding: 8rpx;
    height: 100rpx;
    margin-bottom: 20rpx;
}

.buttons {
    display: flex;
    justify-content: space-around;
}

.send-btn,
.clear-btn {
    background: #4CAF50;
    color: white;
    padding: 12rpx 24rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
}

.clear-btn {
    background: #f44336;
}
</style>